package com.mushuilingfeng.ddd.user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.mushuilingfeng.ddd.user.base.BusinessErrors;
import com.mushuilingfeng.ddd.user.base.UserContext;
import com.mushuilingfeng.ddd.user.bo.UpdatePasswordBO;
import com.mushuilingfeng.ddd.user.bo.UserPersonInfoBO;
import com.mushuilingfeng.ddd.user.cover.IDataCover;
import com.mushuilingfeng.ddd.user.domain.user.entity.User;
import com.mushuilingfeng.ddd.user.domain.user.repository.IUserRepository;
import com.mushuilingfeng.ddd.user.service.ITokenService;
import com.mushuilingfeng.ddd.user.service.IUserService;
import com.mushuilingfeng.ddd.user.vo.UserVO;
import com.mushuilingfeng.spring.security.TokenUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * @author 沐水淋风
 * @date 2024/10/13
 */
@Service("ApplicationUserService")
@AllArgsConstructor
public class UserServiceImpl implements IUserService {
    private final ITokenService tokenService;
    private final IUserRepository userRepository;
    
    @Override
    public void logout() {
        String token = TokenUtil.getToken();
        if (StrUtil.isBlankIfStr(token)) {
            throw BusinessErrors.TOKEN_NOT_EXIST;
        }
        User currentUser = UserContext.getCurrentUser();
        if (null == currentUser) {
            throw BusinessErrors.TOKEN_NOT_EXIST;
        }
        tokenService.deleteToken(token);
    }
    
    @Override
    public void updatePassword(UpdatePasswordBO bo) {
        User user = userRepository.get(UserContext.getCurrentUser().getId());
        user.updatePassword(bo.getOldPassword(), bo.getNewPassword());
        // 清除登陆状态
        logout();
    }
    
    @Override
    public UserVO myInfo() {
        User user = userRepository.get(UserContext.getCurrentUser().getId());
        return IDataCover.INSTANCE.toUserVO(user);
    }
    
    @Override
    public void updateNickName(String nickName) {
        User user = userRepository.get(UserContext.getCurrentUser().getId());
        user.updateNickName(nickName);
    }
    
    @Override
    public void updatePersonInfo(UserPersonInfoBO bo) {
        User user = userRepository.get(UserContext.getCurrentUser().getId());
        user.updatePersonInfo(IDataCover.INSTANCE.toUserPersonInfo(bo));
    }
    
}
